package com.chen.time.triggers;

import com.chen.time.timing.Animator;

public abstract class Trigger {

    private boolean disarmed;
    private Animator animator;
    private TriggerEvent triggerEvent;
    private boolean autoReverse;

    protected Trigger(Animator animator) {
        this(animator, null);
    }

    protected Trigger(Animator animator, TriggerEvent triggerEvent) {
        this(animator, triggerEvent, false);
    }

    protected Trigger(Animator animator, TriggerEvent triggerEvent, boolean autoReverse) {
        this.animator = animator;
        this.triggerEvent = triggerEvent;
        this.autoReverse = autoReverse;
    }

    public void disarm() {
        disarmed = true;
    }

    protected void fire(TriggerEvent currentEvent) {
        if (disarmed) {
            return;
        }
        if (currentEvent == triggerEvent) {
            // event occurred; fire the animation
            if (autoReverse) {
                if (animator.isRunning()) {
                    float f = animator.getTimingFraction();
                    animator.stop();
                    animator.setStartFraction(f);
                } else {
                    animator.setStartFraction(0f);
                }
            }
            if (animator.isRunning()) {
                animator.stop();
            }
            animator.setStartDirection(Animator.Direction.FORWARD);
            fire();
        } else if (triggerEvent != null && currentEvent == triggerEvent.getOppositeEvent()) {
            // Opposite event occurred - run reverse anim if autoReverse
            if (autoReverse) {
                if (animator.isRunning()) {
                    float f = animator.getTimingFraction();
                    animator.stop();
                    animator.setStartFraction(f);
                } else {
                    animator.setStartFraction(1f - animator.getStartFraction());
                }
                animator.setStartDirection(Animator.Direction.BACKWARD);
                fire();
            }
        }
    }

    protected void fire() {
        if (disarmed) {
            return;
        }
        if (animator.isRunning()) {
            animator.stop();
        }
        animator.start();
    }

}
